
import UIKit

class FFTopSpeed: NSObject {

    private let service: String
    
    init(service: String = Bundle.main.bundleIdentifier ?? "com.toolbox.speed") {
        self.service = service
    }
    
    func save(key: String, string: String) -> Bool {
        if let data = string.data(using: .utf8) {
            return save(key: key, data: data)
        }
        return false
    }
    
    func readString(key: String) -> String {
        if let data = read(key: key) {
            return String(data: data, encoding: .utf8) ?? ""
        }
        return ""
    }
    
    
    
    
    private func save(key: String, data: Data) -> Bool {
        
        if let _ = read(key: key) {
            let query: [String: Any] = [
                kSecClass as String: kSecClassGenericPassword,
                kSecAttrService as String: service,
                kSecAttrAccount as String: key
            ]
            
            let attributes: [String: Any] = [
                kSecValueData as String: data
            ]
            
            let status = SecItemUpdate(query as CFDictionary, attributes as CFDictionary)
            return status == errSecSuccess
        } else {
            let query: [String: Any] = [
                kSecClass as String: kSecClassGenericPassword,
                kSecAttrService as String: service,
                kSecAttrAccount as String: key,
                kSecValueData as String: data
            ]
            
            let status = SecItemAdd(query as CFDictionary, nil)
            return status == errSecSuccess
        }
    }
    
    
    private func read(key: String) -> Data? {
        
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: service,
            kSecAttrAccount as String: key,
            kSecReturnData as String: kCFBooleanTrue!,
            kSecMatchLimit as String: kSecMatchLimitOne
        ]
        
        var result: AnyObject?
        let status = SecItemCopyMatching(query as CFDictionary, &result)
        
        if status == errSecSuccess, let data = result as? Data {
            return data
        }
        return nil
    }
}
